<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole">{{
      $t("permission.addRole")
    }}</el-button>

    <el-table
      v-loading="loading"
      :data="
        rolesList.filter(
          data =>
            !search ||
            data.roleName.toLowerCase().includes(search.toLowerCase())
        )
      "
      style="width: 100%; margin-top: 30px"
      border
    >
      <el-table-column align="center" label="编号" width="220">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="权限名称" width="300">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="权限描述">
        <template slot-scope="scope">
          {{
            scope.row.description === null ? "无描述" : scope.row.description
          }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态" width="220">
        <template slot-scope="scope">
          {{ scope.row.disabled === 1 ? "开启" : "关闭" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300">
        <!-- eslint-disable-next-line -->
        <template slot="header" slot-scope="scope">
          <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
        </template>
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">
            {{ $t("permission.editPermission") }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)">
            {{ $t("permission.delete") }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        hide-on-single-page
      >
      </el-pagination>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '修改权限' : `新权限`"
    >
      <el-form
        ref="form"
        :model="role"
        :rules="rules"
        label-width="80px"
        label-position="left"
      >
        <el-form-item label="名称" prop="roleName">
          <el-input v-model="role.roleName" placeholder="请填写权限名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="role.description"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
            placeholder="权限描述"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="role.disabled"
            :active-value="open"
            :inactive-value="close"
            active-color="#1890FF"
            active-text="权限开启"
            inactive-text="权限关闭"
            @change="swchange"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="菜单">
          <el-tree
            ref="tree"
            :check-strictly="checkStrictly"
            :data="routes"
            :props="defaultProps"
            show-checkbox
            node-key="id"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">
          {{ $t("permission.cancel") }}
        </el-button>
        <el-button type="primary" @click="confirmRole">
          {{ $t("permission.confirm") }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { deepClone } from "@/utils";
import { mapState, mapMutations, mapActions, mapGetters } from "vuex";
import { isNullOrEmpty, isArrayLength } from "@/utils/validate";
export default {
  name: "permissions",
  data() {
    // 自定义验证
    const NullOrEmpty = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入权限名"));
      } else if (isNullOrEmpty(value) === true) {
        callback(new Error("请输入权限名"));
      } else {
        callback();
      }
    };
    return {
      rules: {
        roleName: [{ required: true, trigger: "blur", validator: NullOrEmpty }]
      }, // 表单校验规则
      search: "", // 关键字搜索
      loading: true, // 加载圈开启
      role: [], // 每一个权限
      routes: [], // 权限菜单 // 无限树属性

      // 权限列表分页
      page: 1, // 第几页
      pageSize: 3, // 每页几条
      total: 0, // 总条数
      rolesList: [], // 权限列表

      dialogVisible: false, // 编辑弹窗
      dialogType: "new", // 编辑->"edit" 新权限->"new"
      value: 1, // 权限状态
      open: 1, // 开启权限
      close: 0, // 关闭权限
      checkStrictly: false,
      defaultProps: {
        // 无限树属性
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getRolesList();
    this.getRoutes();
  },
  methods: {
    ...mapActions("admin", ["checkRole"]),
    ...mapActions("role", [
      "getRoute",
      "getRoleList",
      "addRole",
      "updateRole",
      "deleteRole"
    ]),

    async undateCheckRole() {
      await this.checkRole();
    },

    // 获取权限列表
    async getRolesList() {
      await this.getRoleList({
        page: this.page,
        pageSize: this.pageSize
      }).then(res => {
        this.total = res.data.total; // 总页数
        this.rolesList = res.data.rolesList; // 权限列表
        this.loading = false; // 关闭加载圈
        this.dialogVisible = false; // 关闭弹窗
      });
    },

    // 切换分页
    handleCurrentChange(val) {
      this.page = val;
      this.getRolesList();
    },

    // 状态
    swchange(e) {
      this.value = e;
    },

    // 获取菜单
    async getRoutes() {
      await this.getRoute().then(res => {
        this.routes = res.data.routers;
      });
    },

    // 添加弹窗
    handleAddRole() {
      this.dialogType = "new"; // 新权限标识
      this.dialogVisible = true; // 开启对话框
      this.checkStrictly = true;
      this.value = 1;
      this.role = {
        disabled: this.value
      }; // 清空填写
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys([]); // 清空树形选项
        this.checkStrictly = false; // 关闭对话框
      });
    },

    // 编辑弹窗
    handleEdit(scope) {
      this.dialogType = "edit"; // 修改权限标识
      this.dialogVisible = true;
      this.checkStrictly = true;
      this.role = deepClone(scope.row); // 获取修改内容（深度克隆）
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(scope.row.permissions.split(",")); // 字符串转数组
        this.checkStrictly = false;
      });
    },

    // 确认修改/添加
    async confirmRole() {
      const CheckedKeys = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys()); // 拼接该用户的权限
      const isEdit = this.dialogType === "edit"; // 判断编辑还是新增
      if (isEdit) {
        this.role.permissions = CheckedKeys.sort((a, b) => {
          return a - b; // 升序的排列
        }).join(); // 数组转字符串
        this.role.disabled = this.value;
        this.$refs["form"].validate(async valid => {
          if (valid) {
            // 修改权限
            await this.updateRole(this.role).then(res => {
              if (res.code === 200) {
                this.getRolesList();
                this.undateCheckRole();
                this.$message({
                  type: "success",
                  message: `${res.msg}!`
                });
              } else {
                this.$message({
                  type: "error",
                  message: `${res.msg}!`
                });
              }
            });
          }
        });
      } else {
        this.role.permissions = CheckedKeys.sort((a, b) => {
          return a - b; // 升序的排列
        }).join(); // 数组转字符串
        this.$refs["form"].validate(async valid => {
          if (valid) {
            // 添加权限
            await this.addRole(this.role).then(res => {
              if (res.code === 200) {
                this.getRolesList(); // 刷新权限列表
                this.$message({
                  type: "success",
                  message: `${res.msg}!`
                });
              } else {
                this.$message({
                  type: "error",
                  message: `${res.msg}!`
                });
              }
            });
          }
        });
      }
    },

    // 删除权限
    handleDelete({ $index, row }) {
      this.$confirm("可能有别的用户是该角色，确认删除角色？", "删除", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await this.deleteRole({ id: row.id }).then(res => {
            // 分页删除最后一条数据，请求上一页
            this.page = this.isLastDel(this.page, this.pageSize, this.total);
            this.getRolesList(); // 刷新权限列表
            this.$message({
              type: "success",
              message: `${res.msg}!`
            });
          });
        })
        .catch(err => {
          console.error(err);
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  .pagination {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin: 20px 0 0 0;
  }
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
